import requests
import json

# 登录获取令牌
def get_token():
    login_url = "http://8.137.14.132:5000/login"
    login_data = {
        "username": "test",
        "password": "test123"
    }
    
    try:
        response = requests.post(login_url, json=login_data)
        if response.status_code == 200:
            token_data = response.json()
            token = token_data.get('token')
            print(f"登录成功！获取到令牌: {token}")
            print(f"用户名: {token_data.get('username')}")
            print(f"是否管理员: {token_data.get('is_admin')}")
            return token
        else:
            print(f"登录失败，状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
            return None
    except Exception as e:
        print(f"请求出错: {str(e)}")
        return None

if __name__ == "__main__":
    token = get_token()
    if token:
        # 保存令牌到文件中，供模拟器使用
        with open("token.txt", "w") as f:
            f.write(token)
        print("令牌已保存到token.txt文件")
        
        # 测试令牌是否有效
        test_url = "http://8.137.14.132:5000/api/verify_token"
        headers = {
            "Authorization": f"Bearer {token}"
        }
        try:
            response = requests.get(test_url, headers=headers)
            print(f"令牌验证结果: {response.status_code}")
            print(json.dumps(response.json(), indent=2, ensure_ascii=False))
        except Exception as e:
            print(f"验证令牌时出错: {str(e)}") 